package Models

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm_study/Table"
	"gorm_study/libs"
)

// SingleRawWrite 单行插入
func SingleRawWrite() {
	libs.DB.AutoMigrate(&Table.Student{}) // 先建表
	//var telephone string
	//telephone = "13212112112"
	student := Table.Student{
		// ID 可以自动增加
		Age: 19,
	}
	err := libs.DB.Create(&student).Error
	if err != nil {
		fmt.Println("创建失败!")
	} else {
		fmt.Printf("创建成功!, ID： %d", student.ID)
	}
}

// ManyRawsWrite 多行插入
func ManyRawsWrite() {
	list := []Table.Student{}
	for i := 0; i < 15; i++ {
		var code string
		if i < 9 {
			code = fmt.Sprintf("天才 #0%d", i+1)
		} else {
			code = fmt.Sprintf("天才 #%d", i)
		}

		list = append(list, Table.Student{
			Name: code,
			Age:  12 + i,
			TEL:  nil,
		})
	}
	err := libs.DB.Create(list).Error
	if err != nil {
		fmt.Println("错误!")
	}

}

// ReadSimple  简单的读取
func ReadSimple() {
	student := Table.Student{}
	libs.DB = libs.DB.Session(
		&gorm.Session{Logger: logger.Default.LogMode(logger.Info)},
	)
	err := libs.DB.Take(&student, "name like ?", "天才 %")
	if errors.Is(err.Error, gorm.ErrRecordNotFound) {
		println("没找到")
	}
	fmt.Println(student) // 每个字段都是默认值
}

// ReadAll 查询
func ReadAll() {
	students := []Table.Student{}                                          // 查询多个数据这里使用的是切片
	count := libs.DB.Find(&students, "name like ?", "天ss才 %").RowsAffected // 获取记录数
	err := libs.DB.Find(&students).Error                                   // 查询失败
	if err != nil {
		fmt.Printf("找到了%d个记录", count)
	} else {
		fmt.Println("查询失败", count)
		fmt.Println(students)
		// 查询失败有: 未找到数据 \ 条件错误 \ 语法错误
	}
}
